package com.nuaa.ange.service.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nuaa.ange.common.lang.RespBean;
import com.nuaa.ange.entity.User;
import com.nuaa.ange.mapper.UserMapper;
import com.nuaa.ange.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuaa.ange.shiro.AccountProfile;
import com.nuaa.ange.utils.RandomUtil;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Service;

/**
 * @description
 * @author 玦离
 * @date 2022/12/30 20:56
 */

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public AccountProfile login(String phoneNumber, String password) {
        User loginUser = this.getOne(new QueryWrapper<User>()
                .eq("phone_number", phoneNumber)
                .eq("user_role", true));
        if(loginUser == null) {
            throw new UnknownAccountException();
        }
        if(!loginUser.getPassword().equals(password)){
            throw new IncorrectCredentialsException();
        }
        AccountProfile profile = new AccountProfile();
        BeanUtil.copyProperties(loginUser, profile);
        return profile;
    }

    @Override
    public RespBean regUser(String phoneNumber) {
        int count = this.count(new QueryWrapper<User>()
                .eq("phone_number", phoneNumber));
        if (count > 0) {
            return RespBean.error("手机号已被注册");
        }
        return RespBean.ok("可以注册");
    }

    @Override
    public RespBean regUserInfo(User user) {
        String salt = RandomUtil.getRandomStringArray();
        user.setSalt(salt);
        user.setNickname(RandomUtil.getRandomStringArray());
        user.setPassword(SecureUtil.md5(user.getPassword() + salt));
        this.save(user);
        user.setUserRole(false);
        this.save(user);
        return RespBean.ok("注册成功");
    }
}
